package cn.vacuumflask.webviewdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private WebView webView;
    private Handler handler;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) this.findViewById(R.id.wv_main);
        handler = new Handler();

        webView.setWebChromeClient(new MyWebChromeClient());
        webView.setWebViewClient(new MyWebViewClient());

        webView.addJavascriptInterface(new ContactInfo(this, webView, handler), "ContactInfo");

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许使用js

        /*
         LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        //开启 DOM storage API 功能 较大存储空间，使用简单
        webSettings.setDomStorageEnabled(true);


        //10M缓存，api 18后，系统自动管理。
        webSettings.setAppCacheMaxSize(10 * 1024 * 1024);
        //允许缓存，设置缓存位置
        webSettings.setAppCacheEnabled(true);
        String appcache = getDir("appcache", 0).getPath();
        Log.d(TAG, "appcache: " + appcache);
        webSettings.setAppCachePath(appcache);
        //允许WebView使用File协议
        webSettings.setAllowFileAccess(true);


        //不支持屏幕缩放
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        //不显示webview缩放按钮
        webSettings.setDisplayZoomControls(false);

        webView.loadUrl("https://www.baidu.com");
//        webView.loadUrl("file:///android_asset/web.html");

    }

    @Override
    protected void onResume() {
        super.onResume();


        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

                    //WebView调用js 拿到返回值

                    webView.evaluateJavascript("javascript:getTagA()", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            Log.d(TAG, "onReceiveValue: " + value);
                        }
                    });

                }
            }
        }, 5 * 1000);


    }


    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {

        Log.i(TAG, "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }

    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {//加载完成
            super.onPageFinished(view, url);
            Log.d(TAG, "onPageFinished: ");

            BufferedReader input = null;
            try {
                StringBuilder javaScript = new StringBuilder();
                InputStream fis = MainActivity.this.getAssets().open("element.js");
                input = new BufferedReader(new InputStreamReader(fis));
                String line = null;
                while ((line = input.readLine()) != null) {
                    javaScript.append(line);
                    //javaScript.append("\n");
                }

                webView.loadUrl("javascript:" + javaScript.toString());

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            super.onPageStarted(view, url, favicon);
            Log.d(TAG, "onPageStarted: ");
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            //如果想拦截某个url的话需要重写shouldOverrideUrlLoading这个方法   返回true拦截（即点击这个链接没有任何反应），返回false不拦截（即这个链接可以正常跳转）

            Log.d(TAG, "shouldOverrideUrlLoading: " + request);
            return super.shouldOverrideUrlLoading(view, request);
        }


    }

    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private class MyWebChromeClient extends WebChromeClient {

        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(MainActivity.this);
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.d(TAG, "网页标题:" + title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.d(TAG, "onProgressChanged: " + newProgress);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除本地图片缓存  不清除cookies
        webView.clearCache(true);
        //清除历史记录  不清除cookies
        webView.clearHistory();

        //释放资源
        if (webView != null) {
            webView.destroy();
            webView = null;
        }
    }

}
